<template>
  <el-dialog :destroy-on-close="true" :title="formData.id?'编辑部门':'新增部门'" :visible="dialogVisible" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @blur="selectBlur">
          <el-option
            v-for="item in employeeList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    nodeData: {
      type: Object,
      default: null
    }

  },
  data() {
    // 检查是否同名
    const checkNameRepeat = async(rule, val, callback) => {
      const { depts } = await getDepartments()
      if (this.formData.id) {
        // 编辑
        const isRepeat = depts.filter(item => item.pid === this.nodeData.pid).some(item => item.name === val && item.id !== this.nodeData.id)
        isRepeat ? callback(new Error(`同级部门下已经有${val}的部门`)) : callback()
      } else {
        // 新增
        const isRepeat = depts.filter(item => item.pid === this.nodeData.id).some(item => item.name === val)
        isRepeat ? callback(new Error(`同级部门下已经有${val}的部门`)) : callback()
      }
    }
    // 检查是否code相同
    const checkCodeRepeat = async(rule, val, callback) => {
      const { depts } = await getDepartments()
      if (this.formData.id) {
        // 编辑
        const isRepeat = depts.some(item => item.code === val && item.id !== this.nodeData.id)
        isRepeat ? callback(new Error(`同级部门下已经有${val}的编码`)) : callback()
      } else {
        // 新增
        const isRepeat = depts.some(item => item.code === val)
        isRepeat ? callback(new Error(`同级部门下已经有${val}的编码`)) : callback()
      }
    }
    return {
      formData: {
        //	string	非必须		部门编码，同级部门不可重复
        code: '',
        //	string	非必须		介绍
        introduce: '',
        //	string	非必须		负责人名称
        manager: '',
        //	string	非必须		部门名称
        name: '',
        //	string	非必须		父级部门ID
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      },
      // 员工列表
      employeeList: []
    }
  },
  async created() {
    this.employeeList = await getEmployeeSimple()
  },
  methods: {
    // 下拉框失焦事件
    selectBlur() {
      setTimeout(() => { // 表单的下拉列表会先失焦，需要延时器
        this.$refs.addForm.validateField('manager')
      }, 100)
    },
    // 确定按钮点击事件
    async btnOK() {
      // 验证整个表单
      await this.$refs.addForm.validate()
      if (this.formData.id) { // 编辑
      // 发送请求编辑部门
        await updateDepartments(this.formData)
        this.$message.success('编辑成功')
      } else { // 新增
        // 发送请求添加部门
        await addDepartments({ ...this.formData, pid: this.nodeData.id })
        this.$message.success('添加成功')
      }
      // 页面更新
      this.$emit('addDepartments')
      // 关闭弹窗
      this.$emit('update:dialogVisible', false)
    },
    // 关闭弹窗后的回调函数
    btnCancel() {
      // 因为编辑时有id等其它数据，所以要重置
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      // 重置弹窗中的数据和校验结果
      this.$refs.addForm.resetFields()
      // 关闭弹窗
      this.$emit('update:dialogVisible', false)
    },
    // 获取部门详情
    async getDepartmentDetail(id) {
      this.formData = await getDepartmentDetail(id)
    }
  }
}
</script>

<style>

</style>
